var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "path", "../../../com/DBTool/DBConnectTool", "../../FSTool/compressible", "../../FSTool/zlibPromise"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const path_1 = __importDefault(require("path"));
    const DBConnectTool_1 = __importDefault(require("../../../com/DBTool/DBConnectTool"));
    const compressible_1 = __importDefault(require("../../FSTool/compressible"));
    const zlibPromise_1 = __importDefault(require("../../FSTool/zlibPromise"));
    async function saveListToDB(DBName, fileInfo) {
        if (!fileInfo.length) {
            return true;
        }
        let fileInfoSqlSum = 'INSERT OR IGNORE INTO file_info  (file_name, file_path, file_zip, file_size, file_md5) VALUES ';
        let fileDataSqlSum = 'INSERT OR IGNORE INTO file_data (file_md5, file_data) VALUES ';
        for (let i = 0; i < fileInfo.length; i++) {
            const fileItem = fileInfo[i];
            if (!fileItem.buffer || !fileItem.relativePath) {
                continue;
            }
            let buffer = fileItem.buffer;
            let compressType = '';
            const relativePath = fileItem.relativePath;
            const md5 = require('crypto').createHash('md5').update(buffer).digest('hex');
            const size = buffer.length;
            const fileName = path_1.default.basename(fileItem.relativePath);
            let file_path = path_1.default.dirname(fileItem.relativePath);
            file_path = file_path === '\\' ? '\\' : file_path + '\\';
            file_path = file_path.replaceAll('/', '\\');
            if (buffer && (0, compressible_1.default)(relativePath) && !fileItem.file_zip) {
                buffer = await zlibPromise_1.default.zip(buffer);
                compressType = 'gzip';
            }
            fileInfoSqlSum += `('${fileName}', '${file_path}', '${compressType}', ${size}, '${md5}'),`;
            fileDataSqlSum += `('${md5}', X'${buffer.toString('hex')}'),`;
        }
        try {
            const dbTool = await DBConnectTool_1.default.openDB(DBName);
            await dbTool.sqlite3Promise.insertData(fileInfoSqlSum.substring(0, fileInfoSqlSum.length - 1), []);
            await dbTool.sqlite3Promise.insertData(fileDataSqlSum.substring(0, fileDataSqlSum.length - 1), []);
            return true;
        }
        catch (e) {
            console.log(e);
            return false;
        }
    }
    exports.default = saveListToDB;
});
